/* $RCSFile: FastAddPage.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Pages/FastAddPage.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:58  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Security;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;


namespace AddonNice.PageModules.Pages
{
 	#region Local TraceSwitch 
	public class FastAddPageTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	            =	new ADNTraceSwitch("FastAddPageTrace","Special Trace Switch for FastAddPageTrace");
	}
	#endregion Local TraceSwitch 

    /// <summary>
	/// This class allows to fastly add a page entering its parent page, users allowed for showing and name
    /// </summary>
	public partial class FastAddPage : PortalModuleControl
	{
        PagesDB pagesDB	    =	new PagesDB();
		/// <summary>
		/// Marks This Module To Be An Admin Module
		/// </summary>
		public override bool AdminModule
		{
			get
			{
				return true;
			}
		}

		/// <summary>
		/// Public constructor. Sets base settings for module.
		/// </summary>
        public FastAddPage()
		{
            ValidationGroup =   "Main";
		}

		#region Page Load

        /// <summary>
		/// The Page_Load event handler on this User Control is used to
		/// load all the modules that are currently on this tab
		/// </summary>
		private void Page_Load(object sender, System.EventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose || FastAddPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage Page_Load BEG IsPostBack: {0}",IsPostBack),(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:FastAddPageTrace.Sw.Info);
   			// If first visit to the page, update all entries
			if ( !IsPostBack ) 
			{
                string msg                              =   LocalizeHelper.Localize("TAB_CONFIRM_ADD", "Confirm adding Module ?");
                string strtitle                         =   LocalizeHelper.Localize("TAB_CONFIRM_TITLE", "Add Page");
                ADNPage.setClientConfirmAttributes(AddPageButton,msg,strtitle);

                TabTitleTextBox.EmptyMessage            =   Helpers.LocalizeHelper.Localize("TAB_NAME", "New Page Name");
		        // Populate the Module Data
                moduleType.SelectFirst  =   true;
                // Select by default Web Page
                tabDropDownList.SelectedTreeViewValue   =   StStr.strPageWebID;
                DataBind();
			}
            // Ajaxified controls
            AddAjaxSetting(AddPageButton,tabDropDownList);
            AddAjaxSetting(AddPageButton,PermissionGrid);
            AddAjaxSetting(AddPageButton,rblAddModuleBuilder);
            AddAjaxSetting(AddPageButton,TabTitleTextBox);
            AddAjaxSetting(AddPageButton,rblJumpToTab);
            AddAjaxSetting(AddPageButton,PanelError);
            portalSettings.ExecForEachMenu(delegate(IPortalMenu menu)
            { AddAjaxSetting(AddPageButton, menu.AjaxControl); });
            if ( ModuleTraceSwitch.Sw.TraceVerbose || FastAddPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage Page_Load END IsPostBack: {0}",IsPostBack),(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:FastAddPageTrace.Sw.Info);
		}
		#endregion

		#region Events

		/// <summary>
		/// Add a new Page to Portal
		/// </summary>
		void AddPageButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
		    if (FastAddPageTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FastAddPage AddPageButton_Click BEG.",FastAddPageTrace.Sw.Info);
			Page.Validate();
            if (!Page.IsValid)
                return;
			if ( string.IsNullOrEmpty(tabDropDownList.Text)  ) // in case validator fails ???
			{
			    if (FastAddPageTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]FastAddPage AddPageButton_Click No page selected.",FastAddPageTrace.Sw.Info);
				moduleError.Text	=	"No Page Selected";
				moduleError.Visible	=	true;
				return;
			}
            
			if ( string.IsNullOrEmpty(TabTitleTextBox.Text)  ) // in case validator fails ???
			{
			    if (FastAddPageTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]FastAddPage AddPageButton_Click No title for page.",FastAddPageTrace.Sw.Info);
				moduleError.Visible	=	true;
				return;
			}
			if (FastAddPageTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage AddPageButton_Click before update module in DB tabDropDownList.SelectedValue: {0}", tabDropDownList.SelectedValue),FastAddPageTrace.Sw.Info);

			StringBuilder viewPermissionRoles			    =   new StringBuilder();
			try
			{
				// Hide error message in case there was a previous error.
				moduleError.Visible							=   false;

				GridItemCollection col                      =   PermissionGrid.SelectedItems;

				foreach (GridItem gr in col)
				{
					if (!gr.Selected || !(gr is GridDataItem) )
						continue;
					string viewPermRoles                    =   ((GridDataItem)gr)["RoleID"].Text;
					if (viewPermRoles == CRMAllUsers)
						viewPermRoles                       =   DBAllUser;
					if (viewPermRoles == CRMAdmin)
						viewPermRoles                       =   DBAdmin;
					if ( !string.IsNullOrEmpty(viewPermRoles))
						viewPermissionRoles.AppendFormat("{0};", viewPermRoles);
				}
			}
			catch(Exception ex)
			{
				moduleError.Visible                         =   true;
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FastAddPage AddPageButton_Click ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}

			try
			{
				// New tabs go to the end of the list
				TabItem t                       =   new TabItem();
				t.Name                          =   TabTitleTextBox.Text;
				t.ID                            =   -1;
				t.Order                         =   990000;

				// Get Parent Tab Id Convert only once used many times
				int parentTabID                 =   int.Parse(tabDropDownList.SelectedValue);


				// write tab to database
                string strPermissionRoles       =   viewPermissionRoles.ToString();
                if ( FastAddPageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage AddPageButton_Click viewPermissionRoles:{0}", strPermissionRoles),FastAddPageTrace.Sw.Info);
                portalSettings.FlushSkinImageMenuCache();
                t.ID                            =   pagesDB.AddPage(portalSettings.PortalID, parentTabID, t.Name,StStr.strDefaultSkin, t.Order
                                                                ,3,0,0,0,0,0,strPermissionRoles);

                ModulesDB modDB			        =	new ModulesDB();
		        ModuleItem m				    =   new ModuleItem();
                // Add Selected Module to page
                if ( FastAddPageTrace.Sw.TraceVerbose)
			        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage AddPageButton_Click SelectedValue is null: {0}.",moduleType.SelectedValue == null),FastAddPageTrace.Sw.Info);
                if ( ( rblAddModule.SelectedValue == "Yes" ) && ( moduleType.SelectedValue != null ))
                {
                    try
			        {
			            // All new modules go to the end of the contentpane
			            string selectedModule	=   moduleType.SelectedValue;

                        if ( FastAddPageTrace.Sw.TraceVerbose)
			                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage AddPageButton_Click SelectedModule: {0}.",selectedModule),FastAddPageTrace.Sw.Info);
            			
			            // Clear error message in case there was a previous error.
			            moduleError.Text        =   string.Empty;

			            // This allows the user to pick what type of people can view the module being added.
			            // If Authorised Roles is selected from the dropdown then every role that has view permission for the
			            // Add Role module will be added to the view permissions of the module being added.
			            int moduleDefID			=   Convert.ToInt32(selectedModule);
				        m.Title					=   string.Format("{0}1",moduleType.Text.Trim());
				        m.ModuleDefID			=   moduleDefID;
				        m.Order					=   1;
				        // save to database
                        if ( FastAddPageTrace.Sw.TraceVerbose)
			                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage AddPageButton_Click save to database newModuleTitle: {0}, moduleDefID: {1}.",
                                m.Title,moduleDefID),FastAddPageTrace.Sw.Info);
                        m.ID					=   modDB.AddModule(t.ID, 
                                                                    m.Order, 
                                                                    0,
                                                                    StStr.contentPane, 
                                                                    m.Title, 
                                                                    m.ModuleDefID, 
                                                                    0, 
                                                                    DBAllUser2, DBAllUser2, DBAllUser2, DBAllUser2, Config.InternalAdminRole, Config.InternalAdminRole, Config.InternalAdminRole, 
                                                                    false, 
                                                                    false);
			        }
			        catch(Exception ex)
			        {
                        if ( ModuleTraceSwitch.Sw.TraceError )
				            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FastAddPage AddPageButton_Click Adding module ex :{0}", ex),ModuleTraceSwitch.Sw.Info);
                        throw;
			        }
                    if ( FastAddPageTrace.Sw.TraceVerbose)
			                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage AddPageButton_Click created ModuleID: {0}",m.ID),FastAddPageTrace.Sw.Info);
                }
                if ( rblAddModuleBuilder.SelectedValue == "Yes" )
                {

                    try
                    {
                        // The new module inherits security from current page current module (current ModuleID) 
                        // so who can edit the tab properties/content can edit the module properties/content (except view that remains =)
                        int AddModuleID     =   modDB.GetModuleDefinitionByGuid(portalSettings.PortalID,new Guid(StStr.AddModuleGuid));
                        if ( AddModuleID > 0 )
                            modDB.AddModule(t.ID,2,0,StStr.rightPane,"Add Module",AddModuleID, 0,
                                                                DBAdmin2, DBAllUser2,
                                                                DBAdmin2, DBAdmin2,
                                                                DBAdmin2, DBAdmin2,
                                                                DBAdmin2, false, false);
                    }
                    catch (Exception ex)
                    {
                        if ( FastAddPageTrace.Sw.TraceError )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FastAddPage Exception inserting 'AddModule' module ex : {0}", ex),FastAddPageTrace.Sw.Info);
                        throw;
                    }
                }
			    portalSettings.ReloadPortal(true);
                portalSettings.ReloadMenus();
                //Jump to Page option
				string returnTab            =   string.Empty;
			    // Redirect to New Page/Tab 
				if ( rblJumpToTab.SelectedValue.ToString() == "Yes" ) 
				{
                    portalSettings.SelectMenuItem(t.ID);
                    returnTab               =   HttpUrlBuilder.BuildUrl(t.ID);
                }
				else
				{
					// Do NOT Redirect to New Form 
				    moduleError.Visible     =   true;
                    moduleError.Text        =   string.Format("{0}-{1} Ok",t.ID,t.Name);
                    TabTitleTextBox.Text    =   string.Empty;
                    return;
                }
                ADNPage.Redirect(returnTab,true);
				//Response.Redirect(returnTab);
			}
			catch(System.Threading.ThreadAbortException)
			{
                // Normal, continue
				throw;
			}
			catch(Exception ex)
			{
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FastAddPage AddPageButton_Click ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}
		}

		#endregion

		#region General Implementation
		/// <summary>
		/// Gets the GUID for this module.
		/// </summary>
		/// <value></value>
		public override Guid GuidID
		{
			get
			{
				return new Guid("{A1E37A0F-4EE9-4b83-9482-43466FC21E08}");
			}
		}
		#endregion

        #region radcontrols
        void PermissionGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
		    if (FastAddPageTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FastAddPage PermissionGrid_NeedDataSource BEG.",FastAddPageTrace.Sw.Info);
            DataTable tbRoles           =   new DataTable();
            tbRoles.Columns.Add("RoleID", typeof(string));
            DataColumn[] keys           =   new DataColumn[1];
            keys[0]                     =   tbRoles.Columns["RoleID"];
            tbRoles.PrimaryKey          =   keys;

            tbRoles.Rows.Add(new object[] { CRMAllUsers });
            // get the CRM Roles
            string[] CrmRoles           =   PortalSecurity.GetCRMRoles();
            foreach (string cr in CrmRoles)
            {
                if ( FastAddPageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FastAddPage OnInit CRMRole:{0}", cr),FastAddPageTrace.Sw.Info);
                DataRow rw              =   tbRoles.NewRow();
                rw[0]                   =   cr;
                tbRoles.Rows.Add(rw);
                }
            PermissionGrid.DataSource = tbRoles;
		    if (FastAddPageTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FastAddPage PermissionGrid_NeedDataSource END.",FastAddPageTrace.Sw.Info);
            }
        
        #endregion radcontrols

		#region Std overrides

        override protected void OnInit(EventArgs e)
		{
		    if (FastAddPageTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FastAddPage OnInit BEG.",FastAddPageTrace.Sw.Info);
            InitializeComponent();
			base.OnInit(e);
		    if (FastAddPageTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FastAddPage OnInit END.",FastAddPageTrace.Sw.Info);
		}

		private void InitializeComponent()
		{
            PermissionGrid.NeedDataSource += new GridNeedDataSourceEventHandler(PermissionGrid_NeedDataSource);
			AddPageButton.Click         +=  new System.Web.UI.ImageClickEventHandler(AddPageButton_Click);
			Load                        +=  new System.EventHandler(this.Page_Load);
		}

		#endregion classic overrides
	}
}
